package com.bolt.core.view.config;

import com.bolt.core.view.templates.FreemarkerTemplateEngine;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.util.Map;
import java.util.Objects;

/**
 * Created by Administrator on 2020/6/3.
 */
@Configuration
@ConditionalOnClass(FreemarkerTemplateEngine.class)
@EnableConfigurationProperties(UIProperties.class)
public class UIAutoConfigure   implements ApplicationListener<ContextRefreshedEvent> {


    @Bean
    public FreemarkerTemplateEngine createTemplateEngine(FreeMarkerConfig config){
        return new FreemarkerTemplateEngine(config.getConfiguration());
    }

    @Bean
    public PageRepository createPageRepository(FreemarkerTemplateEngine engine, UIProperties properties) {
        return new PageRepository(engine,properties);
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Map<String,Object> controllers = event.getApplicationContext().getBeansWithAnnotation(Controller.class);
        PageRepository pageRepository = event.getApplicationContext().getBean(PageRepository.class);
        controllers.forEach((k,v)->{
            RequestMapping mapping =  AnnotationUtils.findAnnotation(v.getClass(), RequestMapping.class);
            if(!Objects.isNull(mapping)){
                String[] paths = mapping.value();
                for(String path : paths){
                    pageRepository.parse(path);
                }
            }
        });
    }
}

 